package com.salmon.study.activiti;


import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.FormService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngineConfiguration;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.form.FormProperty;
import org.activiti.engine.form.TaskFormData;
import org.activiti.engine.impl.form.DateFormType;
import org.activiti.engine.impl.form.StringFormType;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.DeploymentBuilder;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

@Slf4j
public class ActivitiApplication {

    public static void main(String[] args) {
        //1.创建流程引擎
        ProcessEngine processEngine = getProcessEngine();
        //2.部署流程定义文件
        ProcessDefinition processDefinition = getProcessDefinition(processEngine);
        String definitionId = processDefinition.getId();
        //3.启动运行流程
        RuntimeService runtimeService = processEngine.getRuntimeService();
        ProcessInstance processInstance = runtimeService.startProcessInstanceById(definitionId);
        log.info("启动流程{}", processInstance.getProcessDefinitionKey());
        //4.处理流程任务
        TaskService taskService = processEngine.getTaskService();
        Scanner scanner = new Scanner(System.in);
        while (processInstance !=null && !processInstance.isEnded()) {
            Map<String, Object> variables = new HashMap<>(); //流程变量
            List<Task> taskList = taskService.createTaskQuery().list();// 获取所有的任务
            for (Task task : taskList) {
                log.info("待处理任务名称是[{}]", task.getName());
                FormService formService = processEngine.getFormService();
                TaskFormData taskFormData = formService.getTaskFormData(task.getId());
                List<FormProperty> formProperties = taskFormData.getFormProperties();
                for (FormProperty property : formProperties) {
                    String line = null;
                    if(property.getType() instanceof StringFormType) {
                        log.info("请输入[{}]", property.getName());
                        line = scanner.nextLine();
                        variables.put(property.getId(), line);
                    } else if(property.getType() instanceof DateFormType) {
                        log.info("请输入[{}], 格式[yyyy-MM-dd]", property.getName());
                        line = scanner.nextLine();
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        try {
                            Date date = sdf.parse(line);
                            variables.put(property.getId(), date);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    } else {
                        log.info("不支持的类型,[{}]", property.getType());
                    }
                    log.info("输入的内容是[{}]", line);
                }
                taskService.complete(task.getId(), variables);
            }
            log.info("待处理的任务数量[{}]", taskList.size());
            processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstance.getId()).singleResult();
        }
        scanner.close();
    }

    private static ProcessDefinition getProcessDefinition(ProcessEngine processEngine) {
        RepositoryService repositoryService = processEngine.getRepositoryService();
        DeploymentBuilder deploymentBuilder = repositoryService.createDeployment();
        deploymentBuilder.addClasspathResource("second_approve.bpmn20.xml");
        Deployment deploy = deploymentBuilder.deploy();
        String deployId = deploy.getId();
        ProcessDefinition processDefinition =
                repositoryService.createProcessDefinitionQuery()
                .deploymentId(deployId).singleResult();
        log.info("流程定义文件名称是：[{}], 流程定义的ID是[{}]", processDefinition.getName(), processDefinition.getId());
        return processDefinition;
    }

    private static ProcessEngine getProcessEngine() {
        ProcessEngineConfiguration cfg = ProcessEngineConfiguration
                .createProcessEngineConfigurationFromResourceDefault()
                .createStandaloneInMemProcessEngineConfiguration();
        ProcessEngine processEngine = cfg.buildProcessEngine();
        String engineName = processEngine.getName();
        String version = ProcessEngine.VERSION;
        log.info("流程引擎名称是[{}]，版本信息是[{}]", engineName, version);
        return processEngine;
    }
}
